#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/select.h>

void sys_error(const char *msg)
{
    perror(msg);
    exit(1);
}
int kbhit() //检查输入缓冲区是否有东西
{
    struct timeval tv;
    fd_set readfds;
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);
    select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv);
    return FD_ISSET(STDIN_FILENO, &readfds);
}
int main(int argc, char const *argv[])
{
    // int ret = mkfifo("/home/lckfb/Documents/fifo.fifo", 0664);
    // if(ret == -1){
    //     sys_error("creat fifo failed");
    // }

    int fd = open("/home/lckfb/Documents/fifo.fifo", O_WRONLY);
    if(fd == -1)
        sys_error("open fifo failed");

    int i = 0;
    char buf[1024];
    char input;
    printf("Press 'q' to quit.\n");
    while (1)
    {
        sprintf(buf, "message%d\n", i);
        write(fd, buf, strlen(buf));
        if (kbhit())
        {
            input = getchar();
            if (input == 'q')
            {
                break; // 如果输入的是 'q'，则退出循环
            }
        }
        i++;
        sleep(1);
    }
    close(fd);
    return 0;
}
